package com.linln.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linln.common.enums.OrderEnum;
import com.linln.common.enums.RoleEnum;
import com.linln.common.enums.ServiceTypeEnum;
import com.linln.common.enums.TicketEnum;
import com.linln.common.exception.order.OrderException;
import com.linln.common.utils.CodeUtil;
import com.linln.common.utils.DateUtil;
import com.linln.common.utils.SessionUtil;
import com.linln.common.vo.JsonResult;
import com.linln.component.cache.util.RedisUtil;
import com.linln.modules.order.domain.OrderTakecaruser;
import com.linln.modules.order.domain.YearauditOrder;
import com.linln.modules.order.repository.YearauditOrderMapper;
import com.linln.modules.order.service.OrderTakecaruserService;
import com.linln.modules.order.service.YearauditOrderService;
import com.linln.modules.points.domain.Points;
import com.linln.modules.points.service.PointsService;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.repository.UserRepository;
import com.linln.modules.ticket.domain.Ticket;
import com.linln.modules.ticket.domain.TicketLog;
import com.linln.modules.ticket.service.TicketLogService;
import com.linln.modules.ticket.service.TicketService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YearauditOrderServiceImpl extends ServiceImpl<YearauditOrderMapper, YearauditOrder> implements YearauditOrderService {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private TicketLogService ticketLogService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    OrderTakecaruserService orderTakecaruserService;

    @Autowired
    YearauditOrderMapper yearauditOrderMapper;

    @Autowired
    PointsService pointsService;


    @Override
    @Transactional
    public JsonResult buyService(YearauditOrder yearauditOrder,String isBuy) throws OrderException {
        Long userId = SessionUtil.getUserId();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //是否前往redis删除待支付状态key
        boolean flag = false;
        //是否待支付状态进来
        if(Strings.isBlank(yearauditOrder.getStatus())){
            //效验当前用户是否还有未支付的订单
            QueryWrapper<YearauditOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",OrderEnum.WAITPAY.getCode());
            queryWrapper.eq("user_id",userId);
            List<YearauditOrder> yearauditOrderList = super.list(queryWrapper);
            if(yearauditOrderList.size()>0){
                return JsonResult.error("您有待支付状态的订单，请前去支付");
            }
            //否的话new 一些初始化数据
            yearauditOrder.setCreateDate(date);
            yearauditOrder.setOrderNum(CodeUtil.getTimeSerialNoStr());
            yearauditOrder.setUserId(String.valueOf(userId));
            yearauditOrder.setDelFlag("0");
            yearauditOrder.setPickupDelFlag("0");
        }else {
         //效验状态是否为待支付
            if(!OrderEnum.WAITPAY.getCode().equals(yearauditOrder.getStatus())){
                return JsonResult.error("此订单已关闭").setCode(406);
            }
            //删除redis中待支付状态key
            flag = true;
        }

        //是否支付
        if(isBuy.equals("1")){
            //是否使用优惠价
            if(yearauditOrder.getIsTicket()){
                //效验优惠卷
                QueryWrapper ticketWrapper = new QueryWrapper();
                ticketWrapper.eq("ticket_id", yearauditOrder.getTicketId());
                ticketWrapper.eq("user_id",userId);
                Ticket ticket =  ticketService.getOne(ticketWrapper);
                if(ticket==null){
                    throw new OrderException("优惠卷错误");
                }
                ticket.setStatus(TicketEnum.USED.getCode());
                //优惠卷使用记录
                TicketLog ticketLog = new TicketLog();
                ticketLog.setTicketId(ticket.getTicketId());
                ticketLog.setServiceTypeName(ServiceTypeEnum.YEARRWVIEW);
                ticketLog.setShopId(yearauditOrder.getShopId());
                ticketLog.setOperUserId(String.valueOf(userId));
                ticketLog.setVerificationDate(new Date());
                ticketLog.setLicensePlate(yearauditOrder.getPlate());
                ticketService.saveOrUpdate(ticket);
                ticketLogService.save(ticketLog);
                yearauditOrder.setTicketLog(ticketLog.getTicketLogId());
                //服务一些类别对应的操作
                if(yearauditOrder.getService().equals("1") ){
                    yearauditOrder.setPickUpCode(String.valueOf((int)(Math.random()*8998)+1000+1));
                    yearauditOrder.setStatus(OrderEnum.WAITINGCAR.getCode());
                }else {
                    yearauditOrder.setStatus(OrderEnum.COMPLETED.getCode());
                    //自行前往反积分
                    User user = userRepository.getOne(userId);
                    int integral = 100;
                    user.setPointsLeft(user.getPointsLeft()+integral);
                    userRepository.save(user);
                    Points points = new Points();
                    points.setPointsAmount(integral);
                    points.setPointsType(0);
                    points.setExplain("年审办理自行前往反积分");
                    points.setDate(DateUtil.formatDate(new Date()));
                    points.setUserId(String.valueOf(userId));
                    pointsService.save(points);
                }
            }else {
                return JsonResult.error("暂不支持其他方式兑换");
            }
        }else {
            //为待支付状态
            yearauditOrder.setStatus(OrderEnum.WAITPAY.getCode());
        }

        /*---保存汽车年检订单---*/
        super.saveOrUpdate(yearauditOrder);
        if(isBuy.equals("0")){
            //设置未支付状态过期时间
            redisUtil.set(OrderEnum.WAITPAY.name()+"-"+yearauditOrder.getId(),yearauditOrder.getId(),86400);
        }else {
            //改变待支付状态成功删除redis中key的
            if(flag){
                redisUtil.del(OrderEnum.WAITPAY.name()+"-"+yearauditOrder.getId());
            }
        }
        /*---保存成功后返回的值---*/
        Map<String,Object> data = new HashMap<>();
        data.put("service",yearauditOrder.getService());
        data.put("orderId",yearauditOrder.getId());
        return JsonResult.ok().put("data",data);
    }

    @Override
    public void findUserByRoleId(IPage iPage,User user) {
        long page = iPage.getCurrent();
        --page;
        page = page * iPage.getSize();
        int count = userRepository.findByRoleIdConut(RoleEnum.TAKECARUSER.getCode());
        iPage.setTotal(count);
        List<Map<String,Object>> userList = userRepository.findByRoleId(RoleEnum.TAKECARUSER.getCode(),page,iPage.getSize(),user.getNickname(),user.getPhone());
        iPage.setRecords(userList);
    }

    @Override
    @Transactional
    public void saveOrderTakecaruser(String userId, String orderId) throws OrderException {
        YearauditOrder yearauditOrder = super.getById(orderId);
        QueryWrapper<OrderTakecaruser> takecaruserQueryWrapper = new QueryWrapper<>();
        takecaruserQueryWrapper.eq("order_id",orderId);
        OrderTakecaruser orderTakecaruser = orderTakecaruserService.getOne(takecaruserQueryWrapper);

        if(yearauditOrder == null || !OrderEnum.WAITINGCAR.getCode().equals(yearauditOrder.getStatus())){
            throw new OrderException("订单不存在或状态错误");
        }
        User user = userRepository.getOne(Long.valueOf(userId));
        if(user == null){
            throw new OrderException("取车人不存在");
        }
        //如果订单没有取车人就新建一个
        if(orderTakecaruser==null){
            orderTakecaruser = new OrderTakecaruser();
            orderTakecaruser.setOrderId(orderId);
            orderTakecaruser.setCreateDate(DateUtil.formatDate(new Date()));
        }else {
            orderTakecaruser.setUpdateDate(DateUtil.formatDate(new Date()));
        }
        orderTakecaruser.setUserId(Long.valueOf(userId));
        orderTakecaruser.setNickname(user.getNickname());

        orderTakecaruserService.saveOrUpdate(orderTakecaruser);
    }

    @Override
    public void findPickUTheCar(IPage iPage, YearauditOrder yearauditOrder, String takecaruserId) {
        PageHelper.startPage((int) iPage.getCurrent(),(int) iPage.getSize());
        List<YearauditOrder> yearauditOrderList =  yearauditOrderMapper.findPickUTheCar(yearauditOrder.getPhone(),
                yearauditOrder.getContacts(),
                yearauditOrder.getStatus(),
                takecaruserId,
                yearauditOrder.getPickupDelFlag());
        PageInfo<YearauditOrder> pageInfo = new PageInfo<>(yearauditOrderList);
        iPage.setTotal(pageInfo.getTotal());
        iPage.setRecords(yearauditOrderList);
    }


}
